import axios from 'axios'

const API_URL = 'http://localhost:9999'

export default {
    // 使用 Fetch API 处理流式响应
    async sendMessageStream(message, onChunk) {
        try {
            const response = await fetch(`${API_URL}/api/ai/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message })
            })

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`)
            }

            // 处理流式响应
            const reader = response.body.getReader()
            const decoder = new TextDecoder()

            while (true) {
                const { value, done } = await reader.read()
                if (done) break

                const chunk = decoder.decode(value, { stream: true })
                onChunk(chunk)
            }
        } catch (error) {
            console.error('流式请求失败:', error)
            throw error
        }
    },

    // 普通消息发送
    async sendMessage(message) {
        try {
            const response = await axios.post(`${API_URL}/api/ai/chat`, {
                message
            })
            return response
        } catch (error) {
            console.error('AI请求失败:', error)
            throw error
        }
    }
}